package com.qxzn.app.medicalhealth.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.ContactsBean;
import com.qxzn.app.medicalhealth.R;
import com.qxzn.app.medicalhealth.R2;
import com.qxzn.app.medicalhealth.adapter.ChooseUserAdapter;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 选择病历者、选择添加吃药提醒的用户
 */
public class ChooseUserActivity extends BaseActivity {

    @BindView(R2.id.lrv_user)
    LRecyclerView lrvUser;
    @BindView(R2.id.tv_notice)
    TextView tvNotice;
    @BindView(R2.id.view_empty)
    View viewEmpty;
    private LRecyclerViewAdapter recyclerViewAdapter;
    private ChooseUserAdapter adapter;
    private List<ContactsBean.DataBean> dataList = new ArrayList();
    private int page = 1;
    private int pageSize = 10;
    private String title;
    public static final String chooseTitle = "选择病历者";
    public static final String remindTitle = "吃药提醒";

    @Override
    protected int initLayout() {
        return R.layout.activity_choose_user;
    }

    @Override
    protected void initView() {
        adapter = new ChooseUserAdapter(this, dataList);
        recyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        recyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (remindTitle.equals(title)) {
                    startActivityForResult(new Intent(ChooseUserActivity.this, EditRemindActivity.class).putExtra("user_data", dataList.get(position)), 1);
                } else if (chooseTitle.equals(title)) {
                    startActivityForResult(new Intent(ChooseUserActivity.this, AddMedicalRecordActivity.class).putExtra("user_data", dataList.get(position)).putExtra("title", AddMedicalRecordActivity.addMedicalRecord), 1);
                }
                AppUtil.showLog("点击位置：" + position);
            }
        });
        lrvUser.setLayoutManager(new GridLayoutManager(this, 3));
        lrvUser.setEmptyView(viewEmpty);
        lrvUser.setAdapter(recyclerViewAdapter);
        lrvUser.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                AppUtil.showLog("setOnRefreshListener");
                page = 1;
                getData();
            }
        });
        lrvUser.setLoadMoreEnabled(false);
        lrvUser.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                AppUtil.showLog("setOnLoadMoreListener");
                page++;
                getData();
            }
        });
    }

    @Override
    protected void iniTitleBar() {
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        tv_title.setText(title);
        if (remindTitle.equals(title)) {
            tvNotice.setText(R.string.choose_user);
        }
        addMySelfData();
        lrvUser.refresh();
    }

    @OnClick(R2.id.view_empty)
    public void onViewClicked() {
        lrvUser.refresh();
    }

    private void getData() {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                lrvToAuthUser.refreshComplete(pageSize);
//            }
//        }, 1000);
//        for (int i = (page - 1) * pageSize; i < page * pageSize; i++) {
//            dataList.add(new BindRobotUserBean.DataBean());
//        }
//        recyclerViewAdapter.notifyDataSetChanged();
//        recyclerViewAdapter.notifyItemRangeChanged((page - 1) * pageSize, pageSize);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"device_id\":\"" + SharePreferenceUtil.getDeviceId(this) + "\",\"username\":\"" + SharePreferenceUtil.getUserName(this) + "\",\"page\":\"" + page + "\"}");
        Call<ContactsBean> call = HttpRequest.getService().getContacts(body);
        call.enqueue(new Callback<ContactsBean>() {
            @Override
            public void onResponse(Call<ContactsBean> call, Response<ContactsBean> response) {
                lrvUser.refreshComplete(pageSize);
                ContactsBean bean = response.body();
                if (bean != null) {
                    List<ContactsBean.DataBean> deviceList = bean.getData();
                    if (deviceList != null) {
                        if (page == 1) {
                            dataList.clear();
                        }
                        addMySelfData();
                        dataList.addAll(deviceList);
                        adapter.notifyDataSetChanged();
                        recyclerViewAdapter.notifyDataSetChanged();
                        return;
                    }
                }
                if (bean != null && bean.getCode() != 200 && !TextUtils.isEmpty(bean.getMsg())) {
                    AppUtil.showToast(ChooseUserActivity.this, bean.getMsg());
                } else {
                    AppUtil.showToast(ChooseUserActivity.this, "网络错误，请稍后再试！");
                }
            }

            @Override
            public void onFailure(Call<ContactsBean> call, Throwable t) {
                lrvUser.refreshComplete(pageSize);
                AppUtil.showToast(ChooseUserActivity.this, "网络错误，请稍后再试！");
            }
        });
    }

    private void addMySelfData() {
        ContactsBean.DataBean self = new ContactsBean.DataBean();
        self.setMemName(SharePreferenceUtil.getUserName(ChooseUserActivity.this));
        self.setMemRemarks("我");
        self.setAge(SharePreferenceUtil.getAge(ChooseUserActivity.this));
        self.setHeadportrait(SharePreferenceUtil.getPortrait(ChooseUserActivity.this));
        dataList.add(self);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        AppUtil.showLog(resultCode + "---" + requestCode);
        if (resultCode == RESULT_OK && requestCode == 1) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
